package server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import util.CmdParse;

public class Server {
	public void start() throws IOException {
		ServerSocket server = new ServerSocket(9999);
		
		while(true){
			Socket socket = server.accept();
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			out.write("Pls input the command:\n".getBytes());
			
			String command = reader.readLine();
//			System.out.println("tioashi"+command);
			String[] ss = CmdParse.parseCmd(command);
			while(ss == null){
				out.write("the command is invalid, pls input again!\r\n".getBytes());
				command = reader.readLine();
				ss = CmdParse.parseCmd(command);
			}
//			System.out.println("tiaoshi"+ss);
			out.write("200OK\n".getBytes());
			
			if(ss.length == 3){
				String filename = CmdParse.parseFileName(ss[2]);
				filename = filename.substring(1);
				File file = new File(filename);
				
				BufferedWriter writer = new BufferedWriter(new FileWriter(file));
				String tip = null;
				while(!"finished".equals(tip=reader.readLine())){
					writer.write(tip+"\n");
				}
				writer.close();
			}else{
				if(ss[0].equals("LS")){
					File fileLS = new File("remote");
					String[] strings = fileLS.list();
					if(strings.length == 0){
						out.write("no file\n".getBytes());
					}else{
						for (int i = 0; i < strings.length; i++) {
							out.write((strings[i]+"\n").getBytes());
						}
					}
					out.write("end\n".getBytes());
				}else{
					String rmFileName = ss[1];
					File fileRm = new File("remote/"+rmFileName);
					boolean isSucceed = fileRm.delete();
					out.write((isSucceed+"\n").getBytes());
				}
			}
			
			reader.close();
			in.close();
			out.close();
			socket.close();
		}
	}
	
	public static void main(String[] args) throws IOException {
		new Server().start();
	}
}
